/*
 * user-helper.js
 * smart home for amazon echo.
 *
 * Created by cx.
 * Copyright 2019, ttis.
 */

const db = require('./db-base')

/**
 * select query promise
 * @param {string} sql select sql string
 * @param {string} params params string
 * @returns {Promise<Object | boolean>} query promise
 */
exports.selectQuery = (sql, ...params) => new Promise((resolve, reject) => {
  db.getConnection(function(err,client) {
    client.query(sql, params, (err, rows) => {
      client.release();
      if (err) reject({err})
      else resolve(rows.length === 0 ? false : rows[0])
    })
  });
})

/**
 * select query promise
 * @param {string} sql select sql string
 * @param {string} params params string
 * @returns {Promise<Object | boolean>} query promise
 */
exports.selectArrQuery = (sql, ...params) => new Promise((resolve, reject) => {
  db.getConnection(function(err,client) {
    client.query(sql, params, (err, rows) => {
      client.release();
      if (err) reject({err})
      else resolve(rows.length === 0 ? false : rows)
    })
  });
})

/**
 * insert, update, delete query promise
 * @param {string} sql select sql string
 * @param {string} params params string
 * @returns {Promise<Object | boolean>} query promise
 */
exports.alterQuery = (sql, ...params) => new Promise((resolve, reject) => {
  db.getConnection(function(err,client) {
    client.query(sql, params, (err, res) => {
      client.release();
      if (err) reject({err})
      else resolve(res.affectedRows)
    })
  });
})
